<!--
 * @Author: ybf
 * @Date: 2023-02-21 15:31:51
 * @LastEditTime: 2023-12-14 11:57:21
 * @Description: 描述
 * Copyright (c) 2023 by 慧能分享, All Rights Reserved.
-->
<template>
  <div class="diurnalCurve">
    <!-- <nutbTitle title="历史数据"></nutbTitle> -->
    <span class="warning_span">本系统支持查询3个月以内的历史数据，通道中数据变化时，新增一条历史数据</span>
    <NuVerifyForm :model="formData" ref="formData" label-width="100px" class="searchForm" @searchForm="searchForm"
      :buttons="fyButtons">
      <NuformItem label="日期" prop="dataTime" width="320px">
        <el-date-picker v-model="formData.dataTime" type="date" placeholder="请选择日期" style="width: 100%"
          value-format="yyyy-MM-dd" :clearable="false" :picker-options="pickerOptions">
        </el-date-picker>
      </NuformItem>
      <div class="btnBox">
        <nu-button type="primary" class="searchButton" @click="searchLine">搜索</nu-button>
        <nu-button class="searchButton" @click="exportTable">导出</nu-button>
      </div>
    </NuVerifyForm>
    <div class="line"></div>
    <nu-row class="row" :gutter="20">
      <nu-col :span="6" class="col" style="height: 100%">
        <el-radio-group v-model="mesaType" @input="relatedNameInput">
          <el-radio-button v-for="item in typeList" :key="item.dictActualValue" :label="item.dictActualValue">
            {{ item.dictName }}
          </el-radio-button>
        </el-radio-group>
        <nuTree v-model="currentLivingObj.id" :options="treeData" :props="defaultProps" @onClickNode="handleNodeClick">
        </nuTree>
      </nu-col>
      <nu-col :span="18" class="col" style="height: 100%; overflow: hidden">
        <div style="height: calc(100vh - 400px)">
          <nu-echarts width="auto" height="100%" :option="lineOption" class="echarts" v-if="isEchart"></nu-echarts>
        </div>
        <div style="height: 30%">
          <NuTableList :loading="loading" :showFilter="false" :columns="columns" :dataSource="dataSource"
            :options="options" :pagination="pagination" @handleSizeChange="handleSizeChange"
            @handleChangePage="handleChangePage">
          </NuTableList>
        </div>
      </nu-col>
    </nu-row>
  </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue";
import nutbTitle from "@/components/base/tableTitle.vue";
import nuEcharts from "@/components/base/echarts";
import NuVerifyForm from "@/components/verify-form";
import NuformItem from "@/components/verify-form/form-item.vue";
import nuInput from "@/components/base/input";
import nuSelect from "@/components/base/select";
import nuButton from "@/components/base/button";
import NuTableList from "@/components/tableList/TableFormList";
import nuRow from "@/components/base/row.vue";
import nuTree from "@/components/base/tree";
import * as echarts from "echarts";
import { getDateTime } from "@/utils/ruoyi";
import axios from "axios";
export default {
  name: "diurnalCurve",
  components: {
    nuCol,
    nutbTitle,
    nuEcharts,
    NuVerifyForm,
    NuformItem,
    nuInput,
    nuSelect,
    nuButton,
    NuTableList,
    nuRow,
    nuTree,
  },
  data() {
    return {
      formData: { dataTime: "" },
      fyButtons: [],
      isEchart: true,
      lineOption: {
        color: ["#40b0e2", "#69e5c1", "#626b90", "#a0a7e5"],
        title: {
          text: "",
          left: "0",
          textStyle: {
            fontWeight: "normal",
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        xAxis: {
          type: "category",
          data: [],
        },
        yAxis: {
          type: "value",
          name: "",
          scale: true,
        },
        grid: {
          left: "5%",
          right: "3%",
        },
        "dataZoom": [
          {
            "show": true,
            "height": 30,
            "xAxisIndex": [
              0
            ],
            bottom: 10,
            "start": 0,
            "end": 30,
            handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
            handleSize: '110%',
            handleStyle: {
              color: "#d3dee5",

            },
            textStyle: {
              color: "#fff"
            },
            borderColor: "#90979c"
          },
          {
            "type": "inside",
            "show": true,
            "height": 15,
            "start": 1,
            "end": 35
          }
        ],
        series: [
          {
            data: [],
            type: "line",
            showAllSymbol: true,
            symbolSize: 0,
            smooth: false,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(64, 176, 226,0.8)",
                },
                {
                  offset: 1,
                  color: "rgba(64, 176, 226,0.1)",
                },
              ]),
            },
          },
        ],
      },
      dataSource: [],
      columns: [],
      loading: true,
      options: {
        "default-expand-all": true,
        "element-loading-background": "rgba(225,239,242)",
        "element-loading-text": "数据正在加载中",
        "row-key": "pid",
        "header-cell-style": {
          background: "rgba(105, 159, 209, 0.7)",
          color: "#fff",
          fontWeight: "bold",
          fontsize: "16px",
        },
        isNoSetHeight: true,
        height: "100px",
      },
      treeTitle: "",
      treeData: [],
      defaultProps: {
        parent: "parentId", // 父级唯一标识
        value: "id", // 唯一标识
        label: "name", // 标签显示
        children: "children", // 子级
        renderContent: this.renderContent,
        defaultExpandAll: false,
        defaultExpandedKeys: []
      },
      pagination: {
        pageSize: 20,
        total: 0,
        pageNum: 1,
        currentPage: 1
      },
      currentLivingObj: { id: "" },
      mesaType: "201",
      typeList: [
        { dictActualValue: "201", dictName: "遥测" },
        { dictActualValue: "202", dictName: "遥信" },
      ],
      pickerOptions: {
        disabledDate(time) {
          let curDate = new Date().getTime()
          let three = 90 * 24 * 3600 * 1000
          let minTime = curDate - three
          return time.getTime() < minTime || time.getTime() > curDate
        },
      },
    };
  },
  created() { },
  mounted() {
    this.formData.dataTime = getDateTime("day");
    this.getTreeData(this.mesaType);
  },
  methods: {
    /**
     * 查询
     */
    searchLine() {
      this.$refs["formData"].searchForm("form");
    },
    /**
     * form组件内置查询事件
     */
    searchForm(val) {
      if (val) {
        let pagin = JSON.parse(JSON.stringify(this.pagination))
        pagin.pageNum = 1;
        pagin.currentPage = 1;
        this.pagination = null
        this.$nextTick(() => {
          this.pagination = pagin
          this.getDiurnalCurve();
        })
      }
    },
    /**
     * 清除数据
     */
    clearParams() {
      this.resetForm("formData");
    },
    /**
     * 重置表单
     */
    resetForm(formName) {
      this.$refs[formName].resetForm("form");
      for (let k in this[formName]) {
        if (
          Object.prototype.toString.call(this[formName][k]) == "[object String]"
        ) {
          this[formName][k] = "";
        } else if (
          Object.prototype.toString.call(this[formName][k]) == "[object Array]"
        ) {
          this[formName][k] = [];
        } else if (
          Object.prototype.toString.call(this[formName][k]) == "[object Number]"
        ) {
          this[formName][k] = "";
        }
      }
    },
    /**
     * 召唤
     */
    callBtn() { },
    /**
     * 关联input
     */
    relatedNameInput(val) {
      this.mesaType = val;
      this.getTreeData(val);
    },
    /**
     * 导出
     */
    exportTable() {
      if (
        !this.currentLivingObj?.id ||
        this.currentLivingObj.level == 1 ||
        this.currentLivingObj.level == 2 ||
        this.currentLivingObj.level == 3
      ) {
        this.$message({
          type: "info",
          message: "请先选择设备",
        });
        return false;
      }
      let postData = {
        ...this.formData,
        meterId: this.currentLivingObj.modelId,
        nodeName: encodeURIComponent(this.currentLivingObj.name),
        channelId: this.currentLivingObj.channelId,
        groupId: this.currentLivingObj.groupId,
      };
      this.getDownload(window.api.downLoadHisDataFile, {
        ...postData
      }, `历史数据.xlsx`)
    },
    /**
     * 每页条数变化事件
     */
    handleSizeChange(val) {
      this.pagination.pageNum = 1;
      this.pagination.pageSize = val;
      this.getDiurnalCurve();
    },
    /**
     * 改变分页触发事件
     */
    handleChangePage(val) {
      this.pagination.pageNum = val;
      this.getDiurnalCurve();
    },
    /**
     * tree节点单击
     */
    handleNodeClick(item, data) {
      // console.log(item)
      // let box = document.querySelector('.el-tree-node.is-current>.el-tree-node__content')
      // if((item.id == 3)&&(item.modelId == 123)){
      //   box.style.backgroundColor = 'rgba(72, 118, 255, 1)'
      //   console.log(1)
      // }else{
      //   box.style.backgroundColor = 'rgba(248, 249, 252, 1)'
      //   console.log(2)
      // }
      // this.currentLivingObj = item;
      this.currentLivingObj = { ...item, channelId: data.parent.data.modelId, groupId: data.parent.parent.data.modelId };
      this.currentLivingObj["level"] = data.level;
      this.lineOption.title.text = item.name + "变化趋势";
      this.searchForm(true)
    },
    /**
     * 获取曲线数据
     */
    getDiurnalCurve() {
      if (
        !this.currentLivingObj?.id ||
        this.currentLivingObj.level == 1 ||
        this.currentLivingObj.level == 2 ||
        this.currentLivingObj.level == 3
      ) {
        this.$message({
          type: "info",
          message: "请先选择设备",
        });
        return false;
      }
      // let text = this.currentLivingObj.level == 2 ? '母线电压曲线' : '实发功率曲线'
      let postData = {
        ...this.formData,
        meterId: this.currentLivingObj.modelId,
        mesaType: this.mesaType,
        channelId: this.currentLivingObj.channelId,
        groupId: this.currentLivingObj.groupId,
        ...this.pagination,
      };
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.columns = [
        {
          label: "",
          prop: "name",
          width: "220px",
          show: true,
          render: () => { },
        },
      ];
      this.loading = true
      let obj = {},
        xAxis = [],
        series = [];
      this.$httpGet(window.api.getMeterHistoryCharts, postData)
        .then((res) => {
          if (res.code == 200) {
            this.loading = false;
            this.isEchart = false;
            this.pagination.total = res.total
            this.lineOption.xAxis.data = res.energyCharts[0].xaxis;
            this.lineOption.series[0].data = res.energyCharts[0].energys;
            this.columns[0].render = (h, params) => {
              let unit = res.energyCharts[0].unit
                ? `（${res.energyCharts[0].unit}）`
                : "";
              return h("span", params.row.name + unit);
            };
            this.lineOption.tooltip.formatter = (params) => {
              let str = "";
              params.forEach((item) => {
                let unit = res.energyCharts[0].unit
                  ? `（${res.energyCharts[0].unit}）`
                  : "";
                str += `${item.name}<br/>
                            ${item.marker}${item.value}${unit}
                            `;
              });
              return str;
            };
            res.energyCharts[0].tableDatas.forEach((item, i) => {
              this.columns.push({
                label: item.time,
                prop: item.time + i,
              });
              obj[item.time + i] = item.energy;
            });
            obj["name"] = res.energyCharts[0].meterName;
            // this.lineOption.title.text = text
            this.dataSource = [obj];
            this.$nextTick(() => {
              this.isEchart = true;
            });
          } else {
            this.dataSource = [];
          }
        })
        .catch((err) => {
          this.dataSource = [];
        });
    },
    //获取树形控件
    getTreeData(val) {
      let postData = {
        mesaType: val,
      };
      this.defaultProps.defaultExpandedKeys = []
      this.$httpGet(window.api.getHistoryMeterTree, postData)
        .then((res) => {
          if (res.code == 200) {
            let obj = null, channel = null, group = null;
            this.treeData = []
            this.treeData.push(res);
            res.children.forEach((item) => {
              this.defaultProps.defaultExpandedKeys.push(item.id)
              if (item?.children?.[0]?.children?.[0] && !obj) {
                obj = item.children[0].children[0];
                channel = item.children[0]
                group = item
                return false;
              }
            });
            this.currentLivingObj = obj;
            this.currentLivingObj["level"] = 4;
            this.currentLivingObj.id = obj.id;
            this.currentLivingObj.channelId = channel.modelId
            this.currentLivingObj.groupId = group.modelId
            this.getDiurnalCurve();
          } else {
          }
        })
        .catch((err) => { });
    },
    renderContent(h, { node, data, store }) {
      if (node.level == 3 && data.online == 1) {
        return (
          <span class="custom-tree-node mainChannel">
            <span>{node.label}</span>
          </span>);
      } else {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
          </span>);
      }
    }
  },
};
</script>
    
<style scoped lang="scss">
.diurnalCurve {
  height: 100%;
}

.warning_span {
  font-size: 14px;
  font-weight: 600;
  color: var(--button-bgc);
  margin: 0 20px;
}

.el-radio-group {
  margin-left: 20px;
}

.tree {
  height: calc(100vh - 256px);
}

.searchForm {
  // height: calc(100% - 40px);
  display: flex;
  // align-items: center;
  position: relative;
  flex-wrap: wrap;
}

.btnBox {
  display: flex;
  float: right;
  z-index: 10;
  position: absolute;
  top: 15px;
  right: 10px;
}

.row {
  height: calc(100% - 90px);
  width: 100%;
}

// .col {
//     height: 100%;
// }
::v-deep .mainChannel {
  color: rgba(72, 118, 255, 1);
}
</style>
    
    